package com.caizi.base.controller;

import com.caizi.base.dto.UploadRes;
import com.caizi.base.utils.Result;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.UUID;

/**
 * @Author 菜菜籽
 * @Date 2025/5/7 09:06
 * @description: api接口
 */

@RestController
@RequestMapping("/api")
public class APIController {

    @Value("${uploadPath:uploads}")
    private String uploadDir;

    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file) {
        try{
            Path uploadPath = Paths.get(uploadDir);
            if(!Files.exists(uploadPath)) {
                try{
                    Files.createDirectories(uploadPath);
                }catch(IOException e){
                    throw new RuntimeException("无法创建上传目录", e);
                }
            }

            if(file.isEmpty()){
                throw new RuntimeException("文件为空");
            }

            try{
                String uuid = UUID.randomUUID().toString();
                String fileName = uuid + "_"  + file.getOriginalFilename();
                Path filePath = uploadPath.resolve(fileName);
                try (InputStream inputStream = file.getInputStream()) {
                    Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
                } catch (IOException e) {
                    throw new RuntimeException("文件保存失败", e);
                }
//                Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

                UploadRes uploadRes = new UploadRes();
                uploadRes.setName(file.getOriginalFilename());
                uploadRes.setUid(uuid);
                uploadRes.setSize(file.getSize());
                uploadRes.setUrl(fileName);
                uploadRes.setType(file.getContentType());
                uploadRes.setTime(new Date());
                return Result.success(uploadRes);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } catch (Exception e) {
            return Result.fail("上传失败:" + e.getMessage());
        }
    }

    @GetMapping("/download")
    public ResponseEntity<byte[]> viewFile(@RequestParam(name = "fileName", required = true) String fileName){
        try {
            Path uploadPath = Paths.get(uploadDir);
            Path filePath = uploadPath.resolve(fileName);

            // 检查文件是否存在
            if (Files.exists(filePath)) {
                // 读取文件内容
                byte[] fileContent = Files.readAllBytes(filePath);

                // 获取文件扩展名，用于确定Content-Type
                String fileExtension = FilenameUtils.getExtension(fileName).toLowerCase();
                MediaType contentType;
                switch (fileExtension) {
                    case "pdf":
                        contentType = MediaType.APPLICATION_PDF;
                        break;
                    case "html":
                        contentType = MediaType.TEXT_HTML;
                        break;
                    case "txt":
                        contentType = MediaType.TEXT_PLAIN;
                        break;
                    case "jpg":
                        contentType = MediaType.IMAGE_JPEG;
                        break;
                    default:
                        contentType = MediaType.APPLICATION_OCTET_STREAM; // 默认类型
                }

                // 设置HTTP响应头
                HttpHeaders headers = new HttpHeaders();
                // 使用attachment来强制下载文件
                String[] pathSegments = fileName.split("\\\\");
                if(pathSegments.length == 2){
                    fileName = pathSegments[1];
                }
                String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName);
                headers.add(HttpHeaders.CONTENT_TYPE, contentType.toString());

                // 创建并返回ResponseEntity
                return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
            } else {
                // 文件不存在时返回404状态码
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);
            }
        } catch (IOException e) {
            // 处理IO异常并返回500状态码
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
